<?php
/**
@author haohan
@desc 数据库的操作
@data 2009-11-11
@sice 1.0
*/
//if(!defined('haohan')) exit("HTTP/1.1 404 Not Found");
class Mysql{


	/**
	 * @desc  MySQL server  Connect  ID
	 * @see  connect()
	 * @var resource
	 */
	private $link_id = null;
	/**
	 * @desc  Database name
	 * @see  connect()
	 * @see  select_db()
	 * @var String
	 */
	private $dbname;
	/**
	 * @desc Execute  nums
	 * @see  query()
	 * @var resource  or  bool
	 */
	private $querynum = 0;
	/**
	 * @desc debug
	 *
	 * @var Int
	 */
	private $debug = 1;
	private $search = array('/union(\s*(\/\*.*\*\/)?\s*)+select/i', '/load_file(\s*(\/\*.*\*\/)?\s*)+\(/i', '/into(\s*(\/\*.*\*\/)?\s*)+outfile/i');
	private $replace = array('union &nbsp; select', 'load_file &nbsp; (', 'into &nbsp; outfile');
	/**
	 * @desc  Construct  function 。
	 *                Call function connect and assign value to $link_id
	 *
	 */
	function __construct(){
		$config = DBConfig::getConfig();
		$this ->link_id = $this->connect($config['dbhost'], $config['dbuser'], $config['dbpw'], $config['dbname'] , $config['charset'],0 );
	}
	/**
             * @desc  Open a connect to the MySQL server
             *
             * @param String $dbhost
             * @param String $dbuser
             * @param String $dbpw
             * @param Sting $dbname
             * @param Int  $pconnect
             * @param String $charset
             * @return resource   $link_id
             */
	function connect($dbhost, $dbuser, $dbpw, $dbname = '', $charset = '',$pconnect = 0)
	{
		$func = $pconnect == 1 ? 'mysql_pconnect' : 'mysql_connect';
		if(!$this->link_id = @$func($dbhost, $dbuser, $dbpw))
		{
			$this->message('Can not connect to MySQL server');
			return false;
		}
		if($this->version() > '4.1')
		{
			$serverset = $charset ? "character_set_connection='$charset',character_set_results='$charset',character_set_client=binary" : '';
			$serverset .= $this->version() > '5.0.1' ? ((empty($serverset) ? '' : ',')." sql_mode='' ") : '';
			$serverset && mysql_query("SET $serverset", $this->link_id);
		}
		if($dbname && !@mysql_select_db($dbname , $this->link_id))
		{
			$this->message('Cannot use database '.$dbname);
			return false;
		}
		$this->dbname = $dbname;
		return $this->link_id;
	}
	/**
              * @desc Select database
              *
              * @param String $dbname
              * @return bool
              */
	function select_db($dbname)
	{
		if(!@mysql_select_db($dbname , $this->link_id)) return false;
		$this->dbname = $dbname;
		return true;
	}
	/**
             * @desc  Execute the SQL 
             *
             * @param String $sql
             * @param String $type        mysql_query  or   mysql_unbuffered_query
             * @return Execute  results
             *             
             */
	function query($sql , $type = '')
	{
		$func = $type == 'UNBUFFERED' ? 'mysql_unbuffered_query' : 'mysql_query';
		if(!($query = @$func($sql , $this->link_id)) && $type != 'SILENT')
		{
			$this->message('MySQL Query Error', $sql);
			return false;
		}
		$this->querynum++;
		return $query;
	}
	/**
             * @desc Select
             *
             * @param  $sql
             * @param  $keyfield
             * @return Result
             */
	function select($sql, $keyfield = '')
	{
		$array = array();
		$result = $this->query($sql);
		while($r = $this->fetch_array($result))
		{
			if($keyfield)
			{
				$key = $r[$keyfield];
				echo $key;
				$array[$key] = $r;
			}
			else
			{
				$array[] = $r;
			}
		}
		$this->free_result($result);
		return $array;
	}
	/**
             * @desc  Insert  SQL
             *
             * @param String $tablename
             * @param  $array  array('filed=>$value)
             * @return bool
             */
	function insert($tablename, $array)
	{
		$this->check_fields($tablename, $array);
		return $this->query("INSERT INTO `$tablename`(`".implode('`,`', array_keys($array))."`) VALUES('".implode("','", $array)."')");
	}
	/**
             * @desc Update SQL
             *
             * @param Sting $tablename
             * @param $array  array('filed'=>$value)
             * @param String $where
             * @return bool
             */
	function update($tablename, $array, $where = '')
	{
		$this->check_fields($tablename, $array);
		if($where)
		{
			$sql = '';
			foreach($array as $k=>$v)
			{
				$sql .= ", `$k`='$v'";
			}
			$sql = substr($sql, 1);
			$sql = "UPDATE `$tablename` SET $sql WHERE $where";
		}
		else
		{
			$sql = "REPLACE INTO `$tablename`(`".implode('`,`', array_keys($array))."`) VALUES('".implode("','", $array)."')";
		}
		return $this->query($sql);
	}
	/**
             * @desc Get primary KEY
             *
             * @param String $table
             * @return Primary  filed
             */
	function get_primary($table)
	{  
		$result = $this->query("SHOW COLUMNS FROM $table");
		while($r = $this->fetch_array($result))
		{
			if($r['Key'] == 'PRI') break;
		}
		$this->free_result($result);
		return $r['Field'];
	}
	/**
             * @desc Check fileds 
             *
             * @param unknown_type $tablename
             * @param unknown_type $array
             * @return unknown
             */
	function check_fields($tablename, $array)
	{
		$fields = $this->get_fields($tablename);
		foreach($array AS $k=>$v)
		{
			if(!in_array($k,$fields))
			{
				$this->message('MySQL Query Error', "Unknown column '$k' in field list");
				return false;
			}
		}
	}
	/**
              * @desc Get the table fileds
              *
              * @param String $table
              * @return Array  
              */
	function get_fields($table)
	{
		$fields = array();
		$result = $this->query("SHOW COLUMNS FROM $table");
		while($r = $this->fetch_array($result))
		{
			$fields[] = $r['Field'];
		}
		$this->free_result($result);
		return $fields;
	}
	/**
             * @desc  Get a record from database
             *
             * @param String $sql
             * @param String $type    mysql_query  or   mysql_unbuffered_query
             * @return   Result
             */
	function fetch($sql, $type = '')
	{
		$query = $this->query($sql, $type, $expires, $dbname);
		$rs = $this->fetch_array($query);
		$this->free_result($query);
		return $rs ;
	}
	/**
             *  @desc  Fetch an assoc array or num  array from result
             *
             * @param resource $query
             * @param default $result_type   assoc or not
             * @return   result 
             */
	function fetch_array($query, $result_type = MYSQL_ASSOC)
	{
		return mysql_fetch_array($query, $result_type);
	}

	function affected_rows()
	{
		return mysql_affected_rows($this->link_id);
	}
	/**
              * @desc 
              *
              * @param unknown_type $query
              * @return unknown
              */
	function num_rows($query)
	{
		return mysql_num_rows($query);
	}
	/**
              * @desc Fetch the num of fileds from result
              *
              * @param  $query
              * @return Int
              */
	function num_fields($query)
	{
		return mysql_num_fields($query);
	}
	/**
              * @desc Fetch result data
              *
              * @param  $query
              * @param  $row
              * @return  array
              */
	function result($query, $row)
	{
		return @mysql_result($query, $row);
	}
	/**
             * @desc Free result cache
             *
             * @param  $query
             * @return bool
             */
	function free_result(&$query)
	{
		return mysql_free_result($query);
	}
	/**
             * @desc Get the Insert ID
             *
             * @return ID
             */
	function insert_id()
	{
		return mysql_insert_id($this->link_id);
	}
	/**
             * @desc Fetch a row as array from result
             *
             * @param  $query
             * @return array
             */
	function fetch_row($query)
	{
		return mysql_fetch_row($query);
	}
	/**
              * @desc Escape the special char from string
              *
              * @param $string
              * @return  Escape string
              */
	function escape($string)
	{
		if(!is_array($string)) return str_replace(array('\n', '\r'), array(chr(10), chr(13)), mysql_real_escape_string(preg_replace($this->search, $this->replace, $string), $this->link_id));
		foreach($string as $key=>$val) $string[$key] = $this->escape($val);
		return $string;
	}
	/**
              * @desc  Show talbe 's  informations
              *
              * @param String $table
              * @return Array
              */
	function table_status($table)
	{
		return $this->fetch("SHOW TABLE STATUS LIKE '$table'");
	}
	/**
              * @desc  Show talbe info 
              *
              * @return Array
              */
	function tables()
	{
		$tables = array();
		$result = $this->query("SHOW TABLES");
		while($r = $this->fetch_array($result))
		{
			$tables[] = $r['Tables_in_'.$this->dbname];
		}
		$this->free_result($result);
		return $tables;
	}
	/**
             * @desc check talbe exists or not
             *
             * @param String $table
             * @return bool
             */
	function table_exists($table)
	{
		$tables = $this->tables($table);
		return in_array($table, $tables);
	}
	/**
             * @desc check filed  exists or not
             *
             * @param String $table
             * @param String $field
             * @return bool
             */
	function field_exists($table, $field)
	{
		$fields = $this->get_fields($table);
		return in_array($field, $fields);
	}
	/**
              * @desc Fetch MySQL server info
              *
              * @return Array
              */
	function version()
	{
		return mysql_get_server_info($this->link_id);
	}
	/**
             * @desc Close  link
             *
             * @return bool
             */
	function close()
	{
		return mysql_close($this->link_id);
	}
	/**
              * @desc Get error  as text
              *
              * @return String
              */
	function error()
	{
		return @mysql_error($this->link_id);
	}
	/**
             * @desc Get error CODE
             *
             * @return Int
             */
	function errno()
	{
		return intval(@mysql_errno($this->link_id)) ;
	}
           /**
            * @desc Errors message
            *
            * @param  $message
            * @param  $sql
            */
	function message($message = '', $sql = '')
	{
		$this->errormsg = "<b>MySQL Query : </b>$sql <br /><b> MySQL Error : </b>".$this->error()." <br /> <b>MySQL Errno : </b>".$this->errno()." <br /><b> Message : </b> $message";
		if($this->debug)
		{
			$msg = (defined('IN_ADMIN') || DEBUG) ? $this->errormsg : "Bad Request. $LANG[illegal_request_return]";
			echo '<div style="font-size:12px;text-align:left; border:1px solid #9cc9e0; padding:1px 4px;color:#000000;font-family:Arial, Helvetica,sans-serif;"><span>'.$msg.'</span></div>';
			exit;
		}
	}
}
?>